// import 'babel-polyfill'
import Vue from 'vue';
import store from './store'
import axios from 'axios'// 第三方库
import App from './App.vue'
import router from './router'
import $ from 'jquery'
import { Toast, Lazyload } from 'vant';
import { Dialog } from 'vant';
import { TreeSelect, Collapse, CollapseItem } from 'vant';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import 'viewerjs/dist/viewer.css'
import * as echarts from 'echarts'
import Vant from 'vant';
import {Icon} from 'vant'
import 'lib-flexible/flexible.js';
import 'vant/lib/index.css';
// import { baseAplus } from '@/utils/maidian.js'
import { fitChartSize } from '@/utils/echartUtils.js'
import vueEsign from 'vue-esign'
import getToPng from './utils/getToPng'
import htmlToPdf from './utils/pdfTo'
import htmlToPdf1 from './utils/pdftopng'
import VueSweetalert2 from './utils/vue-sweetalert2'
// import {FixedNav, Drag, Popup } from '@nutui/nutui';
// import NutUI from '@nutui/nutui';
// import '@nutui/nutui/dist/nutui.css';
// import chalk from '../src/utils/console.ts';
import chalk from '@alita/chalk';
import BScroll from '@better-scroll/core'
import ObserveDom from '@better-scroll/observe-dom'
import Mui from 'vue-awesome-mui';
import { preventReClick } from './utils/plugins'
import BaiduMap from 'vue-baidu-map'
// 引入自定义的 confirm 弹框
import myConfirm from './utils/index.js'
import  FastClick  from  'fastclick'
// import Driver from 'driver.js'
// import 'driver.js/dist/driver.min.css'
import { VueJsonp } from 'vue-jsonp'
import sendPublic from './components/NewZzd/public/sendPublic'
Vue.component('sendPublic', sendPublic)
Vue.use(VueJsonp)
Vue.use(Icon);
// NutUI.install(Vue);
// FixedNav.install(Vue);
// Drag.install(Vue);
// Popup.install(Vue);
// // 将方法写入到 Vue 原型上
// Vue.prototype.$driver = new Driver({
// 	doneBtnText: '完成', // 最后一个按钮的文本
//   	closeBtnText: '关闭', // 关闭按钮文本
//   	stageBackground: '#f60', // 高亮显示的元素的背景色
//   	nextBtnText: '下一步', // 下一步
//   	prevBtnText: '上一步', // 上一步
// })
Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: 'BDv3WGThhC19xh6bVCjALzUscGSWxzaS'
})
//哨兵模式
// import * as Sentry from "@sentry/browser";
// import { BrowserTracing } from "@sentry/tracing";
Vue.config.productionTip = false
Vue.use(Mui);
Vue.use(preventReClick)
BScroll.use(ObserveDom)

Vue.use(VueSweetalert2)
Vue.use(TreeSelect);
Vue.use(Collapse);
Vue.use(CollapseItem);
Vue.use(Toast);
Vue.use(Lazyload);
Vue.use(htmlToPdf)
Vue.use(getToPng)
Vue.use(htmlToPdf1)
Vue.use(vueEsign);
Vue.use(ElementUI);
// Vue.use(chalk)
Vue.prototype.$echarts = echarts
Vue.prototype.fitChartFont = fitChartSize
Vue.prototype.$axios = axios
window.alitadebug = true;
Vue.prototype.$confirm = myConfirm

// 开启哨兵模式chalk.hello('Malita', '0.0.6');
// Sentry.init({
//   dsn: "http://e30623077c5342ee9019b5266b4752c9@localhost:9000/2",
//   integrations: [new BrowserTracing()],

//   // Set tracesSampleRate to 1.0 to capture 100%
//   // of transactions for performance monitoring.
//   // We recommend adjusting this value in production
//   tracesSampleRate: 1.0,
// });
FastClick.prototype.focus = function (targetElement) {
  let length;
  //这是因为这些元素并没有selectionStart和selectionEnd的整型数字属性，所以一旦引用就会报错，因此排除这些属性才使用setSelectionRange方法
  if (targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
    length = targetElement.value.length;
    targetElement.focus();
    targetElement.setSelectionRange(length, length);//修复bug ios 11.3不弹出键盘，这里加上聚焦代码，让其强制聚焦弹出键盘
  } else {
    targetElement.focus();
  }
};
FastClick.attach(document.body);
Array.prototype.remove = function (item, all) {
  var result, isType = Object.prototype.toString, i, len, start, hasLast = arguments[2];
  start = 0, len = this.length;
  for (i = start; i < len;) {
    var isPass = true, inx;
    if (!hasLast) {
      inx = i;
    } else {
      inx = len - 1;
    }
    if (isType.call(item) == '[object Array]') {
      for (var ii = 0, iimax = item.length; ii < iimax; ii++) {
        if (this[inx] === item[ii]) {
          isPass = false;
          break;
        }
      }
    } else if (this[inx] === item) {
      isPass = false;
    }
    if (!isPass) {
      result = true;
      this.splice(inx, 1);
      if (all) {
        break;
      }
    } else if (!hasLast) {
      len = this.length;
      i++;
    } else {
      len--;
    }
  }
  return result ? this : void 0;
}
// Vue.use(MintUI);
Vue.use(Vant);
Vue.use(Dialog);
// dd.getAuthCode({}).then((result) => {
//     if (result) {
//         // code: 'hYLK98jkf0m' //string authCode
//         window.localStorage.setItem('getauthCode', JSON.stringify(result.code, null, null))
//         window.alert(result.code)
//     }
// })
Vue.directive('preventReClick', {
  inserted(el, binding) {
    el.addEventListener('click', () => {
      if (!el.disabled) {
        el.disabled = true
        setTimeout(() => {
          el.disabled = false
        }, binding.value || 2000)
      }
    })
  }
})
// Vue.prototype.UploadOrCreateGroup = function (rowGuid, groupName, file) {
//   let me = this;
//   let fileData = null;
//   fileData = new FormData();
//   fileData.append("file", file);
//   fileData.append("rowGuid", rowGuid);
//   fileData.append("groupName", groupName);
//   fileData.append("token", store.state.token);
//   let url = window.g.BaseURL +
//     "/EcaServices/EcaFileManagerServer/UploadOrCreateGroup";
//   return new Promise((resovlve, reject) => {
//     $.ajax({
//       url: url,
//       type: "post",
//       data: fileData,
//       //ajax2.0可以不用设置请求头，但是jq帮我们自动设置了，这样的话需要我们自己取消掉
//       contentType: false,
//       dataType: "json",
//       //取消帮我们格式化数据，是什么就是什么
//       processData: false,
//       success: function (res) {
//         // if(Eca && Eca.OprationLog){
//         //   Eca.OprationLog.OprationLogFile('上传附件', undefined, res.fileList);
//         // }
//         resovlve(res)
//       }
//     })
//   })
// };
Vue.prototype.newGuid = function (format) {
  //表示全局唯一标识符 (GUID)。
  function Guid(g) {
    var arr = new Array(); //存放32位数值的数组
    if (typeof g == "string") {
      //如果构造函数的参数为字符串
      InitByString(arr, g);
    } else {
      InitByOther(arr);
    }
    //返回 Guid 类的此实例值的 String 表示形式。
    this.ToString = function (format) {
      if (typeof format == "string") {
        if (format == "N" || format == "D" || format == "B" || format == "P") {
          return ToStringWithFormat(arr, format);
        } else {
          return ToStringWithFormat(arr, "D");
        }
      } else {
        return ToStringWithFormat(arr, "D");
      }
    };
    //由字符串加载
    function InitByString(arr, g) {
      g = g.replace(/\{|\(|\)|\}|-/g, "");
      g = g.toLowerCase();
      if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {
        InitByOther(arr);
      } else {
        for (var i = 0; i < g.length; i++) {
          arr.push(g[i]);
        }
      }
    }

    //由其他类型加载
    function InitByOther(arr) {
      // var i = 32;
      // while (i--) {
      //     arr.push("0");
      // }

      var i = 32;
      while (i--) {
        arr.push(Math.floor(Math.random() * 16.0).toString(16));
      }
    }

    /*
        根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。
        N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
        B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
        P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
        */
    //增加一个标识能区分开这个guid是不是由前端生成的
    function ToStringWithFormat(arr, format) {
      switch (format) {
        case "N":
          return arr.toString().replace(/,/g, "");
        case "D":
          var str =
            arr.slice(0, 8) +
            "-1203" +
            "-" +
            arr.slice(12, 16) +
            "-" +
            arr.slice(16, 20) +
            "-" +
            arr.slice(20, 32);
          str = str.replace(/,/g, "");
          return str;
        case "B":
          var str = ToStringWithFormat(arr, "D");
          str = "{" + str + "}";
          return str;
        case "P":
          var str = ToStringWithFormat(arr, "D");
          str = "(" + str + ")";
          return str;
        default:
          return new Guid();
      }
    }
    return this.ToString();
  }
  var g = new Guid();
  return g.ToString(format);
}
Vue.prototype.shuiyin = function ({
  container = document.body,
  url = "",
  width = '200px',
  height = '150px',
  textAlign = 'center',
  textBaseline = 'middle',
  font = "18px Microsoft Yahei",
  fillStyle = "rgba(255, 255, 255, .8)",
  content = "",
  rotate = '30',
  cb = null,
  zIndex = 1000
} = {}) {
  let _this = this
  const img = new Image();
  img.src = url;
  img.crossOrigin = "anonymous";
  img.onload = function () {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext('2d')
    canvas.width = img.width;
    canvas.height = img.height
    ctx.drawImage(img, 0, 0)
    // const waterMarkCanvas = createWaterMark(content)
    // ctx.fillRect(0, 0, canvas.width, canvas.height)
    let fontSize = 20 * (img.width / 375) + 'px'
    console.log(20 * (img.width / 375) + 'px')
    ctx.font = fontSize + '0 黑体'
    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
    ctx.textAlign = 'left'
    ctx.textBaseline = 'Middle'
    ctx.fillText('时间：' + content, 20, img.height - 30)
    const base64Url = canvas.toDataURL();
    cb && cb(base64Url);
  };
}
Vue.prototype.dataURLtoFile = function (dataurl, filename) {
  var arr = dataurl.split(',');
  var mime = arr[0].match(/:(.*?);/)[1];
  var bstr = atob(arr[1]);
  var n = bstr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  //转换成file对象
  return new File([u8arr], filename, { type: mime });
  //转换成成blob对象
  //return new Blob([u8arr],{type:mime});
}

/**
 * 使用Vue.directive声明自定义指令v-has
 * inserted：被绑定元素插入父节点时调用
 * el：指令所绑定的元素，可以用来直接操作 DOM
 * binding.value：指令的绑定值，例如：v-has="Home" 中，绑定值为 Home。
 * 使用示例 <el-button v-has="'Home'">权限按钮1</el-button>
 */
function checkArray(data) {
  if (data == '16635049159') {
    return true
  } else {
    return false
  }
}
Vue.directive('has', {
  inserted: function (el, binding) {
    let permission = binding.value // 获取到 v-has的值
    // console.log(permission, 'permission+++++++++++++++++++++++')
    // 代表某个元素需要通过权限验证
    if (permission) {
      let hasPermission = checkArray(permission)
      // console.log(menuList, hasPermission, 'hasPermission++++++++++++')
      if (hasPermission) {
        // 没有权限 移除Dom元素
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
})

Vue.prototype.getDate = function (data) {
  let dateTime
  let yy = new Date().getFullYear()
  let mm = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
  let dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
  let minutes = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
  let seconds = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
  let strDate = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
  if (data) {
    dateTime = yy + '-' + mm + '-' + dd
  } else {
    dateTime = yy + '-' + mm + '-' + dd + " " + seconds + ':' + minutes + ':' + strDate
  }

  return dateTime
}
//判断内容是否为空
Vue.prototype.IsEmpty=function(value){
  if (value === null) {
    return true;
  }
  switch (typeof value) {
    case "undefined":
      return true;

    case "number":
      return isNaN(value);

    case "string":
      return value.trim() === "";

    case "object":
      var countKeys = Object.keys(value).length;
      return countKeys < 1;

    default:
      console.log("Undefined value type", "isEmpty");
      return false;
  }
}
//行政区划过滤
Vue.prototype.getCityCode = function () {
  let nowUserCode = window.localStorage.getItem("citycode");
  if (nowUserCode) {
    if (nowUserCode.substring(0, 12) === "330000000000")
      nowUserCode = nowUserCode.substring(0, 2)
    else if (nowUserCode.substring(4, 12) === "00000000")
      nowUserCode = nowUserCode.substring(0, 4)
    else if (nowUserCode.substring(6, 12) === "000000")
      nowUserCode = nowUserCode.substring(0, 6)
    else if (nowUserCode.substring(9, 12) === "000")
      nowUserCode = nowUserCode.substring(0, 9)
  }
  // localStorage.setItem("citycodes", nowUserCode)
  return nowUserCode

},
  //获取当前url地址 并切割& 获得长度
  //得到网址参数
  // router.beforeEach((to, from, next) => {
  //   let token = window.localStorage.getItem('token')
  //   if(token || process.env.NODE_ENV == 'production'){
  //     next()
  //   }else{
  //     if(to.path == '/Login'||to.path == 'zhezhengdingLogin'){
  //       next()
  //     } else{
  //       next({
  //         //需要根据不同的系统修改当前值
  //         path:"/zhezhengdingLogin"
  //       })
  //     }
  //   }
  // });
  router.beforeEach((to, from, next) => {
    // console.log(to,from,'vmkidnmjvikdnvikn')
    // baseAplus(to)
    if (from.name == 'mapContainer') {
      next()
      //判断是从哪个路由过来的，
    }
    if (to.name === 'qianming') {
      if (!from.meta.keepAlive) {
        from.meta.keepAlive = true // 当我们进入到C时开启对B页面的缓存
      }
      next()
    } else {
      from.meta.keepAlive = false
      // this.$destroy() // 销毁B的实例
      next()
    }
  })
/*ajax 拦截添加token到body*/


// $.ajaxSetup({
//   dataType: "json",
//   cache: false,
//   beforeSend: function () {
//     if (arguments[1].url.indexOf('UploadOrCreateGroup') == -1 && arguments[1].url.indexOf('Upload') == -1) {
//       let data = qs.parse(arguments[1].data);
//       data.token = store.state.token;
//       arguments[1].data = qs.stringify(data);
//     }

//   }
// });
new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')
